package com.zjitc.controller;

import com.google.gson.Gson;
import com.zjitc.model.User;
import com.zjitc.service.UserService;
import com.zjitc.utils.rabbit.RabbitMessage;
import com.zjitc.utils.redis.MyRedis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.InternalResourceView;
import redis.clients.jedis.Jedis;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.NoSuchAlgorithmException;
import java.util.Set;

/**
 * @author Administrator
 */
@Controller
@RequestMapping(value = "/user")
public class UserControl {

    @Autowired
    private UserService service;
    @Autowired
    private RabbitMessage message;
    @Autowired
    private MyRedis redis;

    @RequestMapping(value = "/hello")
    @ResponseBody
    public String hello2() {
        return "hello...";
    }

    @RequestMapping(value = "/test")
    @ResponseBody
    public ModelAndView test() {
        return null;
    }

    @RequestMapping(value = "/register")
    @ResponseBody
    public ModelAndView register(User user) {
        Gson gson = new Gson();
        String s = gson.toJson(user);
        int i = message.sendMessage("U" + s);
        ModelAndView view = new ModelAndView(new InternalResourceView("/jsp/msg.jsp"));
        String msg;
        String address;
        if (i > 0) {
            msg = "注册成功，请登陆邮箱激活账号";
            address = "/jsp/login.jsp";
        } else {
            msg = "注册失败";
            address = "/jsp/register.jsp";
        }
        view.addObject("msg", msg);
        view.addObject("address", address);
        return view;
    }

    @RequestMapping(value = "/checkUserName")
    @ResponseBody
    public String checkUserName(String username) {
        boolean b = service.verifyUsername(username);
        if (b) {
            //不为空，用户名已经存在，不可以注册
            return String.valueOf(1);
        } else {
            return String.valueOf(-1);
        }
    }

    @RequestMapping(value = "/active")
    public ModelAndView active(String uid, String code) {
        boolean success = service.active(uid, code);
        ModelAndView view = new ModelAndView(new InternalResourceView("/jsp/msg.jsp"));
        String msg;
        String address;
        if (success) {
            msg = "激活成功，即将到登录页面";
            address = "/jsp/login.jsp";
        } else {
            msg = "激活失败";
            address = "/jsp/register.jsp";
        }
        view.addObject("msg", msg);
        view.addObject("address", address);
        return view;
    }

    @RequestMapping(value = "/login")
    @ResponseBody
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password, HttpSession session)
            throws UnsupportedEncodingException, NoSuchAlgorithmException {
        int i = service.login(username, password, session);
        return Integer.toString(i);
    }

    /**
     * 用户未激活
     */
    @RequestMapping(value = "/notActive")
    public String notActive(Model model) {
        String msg = "该账号还未激活，请先登录注册的邮箱账号进行激活";
        String address = "/jsp/login.jsp";
        model.addAttribute("msg", msg);
        model.addAttribute("address", address);
        return "/jsp/msg.jsp";
    }

    /**
     * 注销登录
     */
    @RequestMapping(value = "/loginOut")
    public String loginOut(Model model, HttpSession session) {
        User user = (User) session.getAttribute("user");
        Set<String> strings = redis.smembers(user.getUid() + "search");
        for (String str : strings) {
            redis.del(str);
        }
        redis.del(user.getUid() + "search");
        redis.del(user.getUid() + "order");
        session.removeAttribute("user");
        User one = (User) session.getAttribute("user");
        if (one == null) {
            return "redirect:/index.do?";
        } else {
            return String.valueOf(-1);
        }
    }

    @RequestMapping(value = "/autoLogin")
    @ResponseBody
    public String autoLogin(String username, String password, HttpServletRequest request,
                            HttpSession session, HttpServletResponse response)
            throws IOException, NoSuchAlgorithmException, ServletException {
        int i = service.login(username, password, session);
        if (i == 1) {
            User user = (User) session.getAttribute("user");
            Gson gson = new Gson();
            String s = gson.toJson(user);
            String ss = URLEncoder.encode(s, "utf-8");
            Cookie cookie = new Cookie("user", ss);
            cookie.setMaxAge(60);
            response.addCookie(cookie);
            int state = 100;
            if (user.getState() == state) {
                return String.valueOf(100);
            }
            return String.valueOf(1);
        } else {
            return Integer.toString(-1);
        }
    }
}
